package br.unifor.cct.mia.coevolution.evaluate;

import java.io.IOException;

import br.unifor.cct.mia.coevolution.CoevolutionaryDomain;
import br.unifor.cct.mia.coevolution.InvalidTypeException;
import br.unifor.cct.mia.dataenhancement.Database;
import br.unifor.cct.mia.dataenhancement.Structure;
import br.unifor.cct.mia.evaluate.Evaluate;
import br.unifor.cct.mia.evolutionary.SpeciesConstants;
import br.unifor.cct.mia.ga.Ga;

public class CoevolutionaryEvaluation implements Evaluate {

	public Object evaluate(Object value,String[] options) {
		Object[] o = (Object[]) value;
		CoevolutionaryDomain domain = (CoevolutionaryDomain)o[0];
		Integer specieType = (Integer)o[1];
		Structure struc = (Structure)o[2];
		Database db = (Database)o[3];
		Ga ga = (Ga)o[4];
		
		int nBits = 0;
		if ( specieType==SpeciesConstants.HUGE_SCALE_FEATURE_SELECTION ) {
			nBits = (Integer)o[6];
		}
		
		ga.sum = 0;
		ga.indexBestWorst[0] = ga.indexBestWorst[1] = 0;
       
		
        for(int i = 0; i < ga.configurations.getPopsize(); i++) {        	
        	        	
			try {
				domain.evaluate(ga.population[i],specieType.intValue(),struc,db,nBits);				
			} catch (IOException e) {				
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (InvalidTypeException e) {				
				e.printStackTrace();
			}   
        	        	
	        if (ga.population[i].getFitness() > ga.population[ga.indexBestWorst[0]].getFitness()) {	        	
		        ga.indexBestWorst[0] = i;
	        }
	        else if (ga.population[i].getFitness() < ga.population[ga.indexBestWorst[1]].getFitness()) {
	           	ga.indexBestWorst[1] = i;
	        }        	
            	
            ga.sum += ga.population[i].getFitness();
        }
        
		return ga.population;
	}
	
}
